//
//  XMN_ReadTypeDetailViewController.m
//  B段项目
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "XMN_ReadTypeDetailViewController.h"
#import "XMN_TypeList.h"
#import "XMN_TypeWrite.h"
#import "XMN_ReadTypeCell.h"
#import "XMN_ReadTypeWithoutImageCell.h"
#import "XMN_ReadDetailViewController.h"

@interface XMN_ReadTypeDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)myButton *hotButton;
@property(nonatomic, strong)myButton *newestButton;
@property(nonatomic, strong)UILabel *hotlabel;
@property(nonatomic, strong)UILabel *newestlabel;
@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, assign)NSInteger start;
@property(nonatomic, strong)NSString *str;
@property(nonatomic, strong)XMN_ProgressHUD *HUD;
@end

@implementation XMN_ReadTypeDetailViewController

-(void)loadView{
    [super loadView];
    
    //初始化数组
    _dataSourceArray = [NSMutableArray array];
    _str = @"hot";
    if (_whichOne == 1) {
        [self getWritingDataByURLString];
    }else{
        [self getDataByURLString];
    }
    
    //初始化button
    _hotButton = [myButton buttonWithType:UIButtonTypeSystem];
    _hotButton.frame = CGRectMake(0, 0, ScreenWidth / 2.0, 40 * FitHeight);
    [_hotButton setTitle:@"最热" forState:UIControlStateNormal];
    [self.view addSubview:_hotButton];
    _hotlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _hotButton.frame.size.height, _hotButton.frame.size.width, 1 * FitHeight)];
    _hotlabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_hotlabel];
    
    _newestButton = [myButton buttonWithType:UIButtonTypeSystem];
    _newestButton.frame = CGRectMake(_hotButton.frame.size.width, 0, _hotButton.frame.size.width, _hotButton.frame.size.height);
    [_newestButton setTitle:@"最新" forState:UIControlStateNormal];
    [self.view addSubview:_newestButton];
    _newestlabel = [[UILabel alloc]initWithFrame:CGRectMake(_newestButton.frame.origin.x, _newestButton.frame.size.height, _newestButton.frame.size.width, 1 * FitHeight)];
    _newestlabel.backgroundColor = [UIColor grayColor];
    _newestlabel.alpha = 0;
    [self.view addSubview:_newestlabel];
    
    [_hotButton addTarget:self action:@selector(hotbuttonAction) forControlEvents:UIControlEventTouchUpInside];
    [_newestButton addTarget:self action:@selector(newestbuttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //初始化tableView
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView NightWithType:UIViewColorType2];
    [self.view addSubview:_tableView];
    
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
    
    //刷新加载
//    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        _start = 0;
//        if (_whichOne == 1) {
//            [self getWritingDataByURLString];
//        }else{
//            [self getDataByURLString];
//        }
//    }];
//    
//    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _start++;
//        if (_whichOne == 1) {
//            [self getWritingDataByURLString];
//        }else{
//            [self getDataByURLString];
//        }
//    }];
//    if (_whichOne == 1) {
//                    [self getWritingDataByURLString];
//                }else{
//                   [self getDataByURLString];
//            }

   MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    _tableView.header = header;
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 1; i <= 9; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lda", i]];
        [array addObject:image];
    }
    [header setImages:array duration:1 forState:MJRefreshStatePulling];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    _tableView.footer = footer;
    [footer setImages:array duration:1 forState:MJRefreshStateRefreshing];
    [_tableView.header beginRefreshing];

}
-(void)getData
{
    if (_whichOne == 1) {
                    [self getWritingDataByURLString];
                }else{
                    [self getDataByURLString];
                }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (_whichOne == 1) {
        self.title = _titleString;
    }else{
      self.title = _list.name;  
    }
    
    // Do any additional setup after loading the view.
}

#pragma mark - button点击事件
-(void)hotbuttonAction{
    [_tableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 1;
        _newestlabel.alpha = 0;
    }];
    _str = @"hot";
    _start = 0;
    if (_whichOne == 1) {
        [self getWritingDataByURLString];
    }else{
        [self getDataByURLString];
    }
}

-(void)newestbuttonAction{
    [_tableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 0;
        _newestlabel.alpha = 1;
    }];
    _start = 0;
    _str = @"addtime";
    if (_whichOne == 1) {
        [self getWritingDataByURLString];
    }else{
        [self getDataByURLString];
    }
}

#pragma mark - tableView相关设置
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSourceArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_whichOne == 1) {
        XMN_TypeWrite *typeWrite = [_dataSourceArray objectAtIndex:indexPath.row];
        if ([typeWrite.firstimage isEqualToString:@""]) {
            static NSString *identifier = @"cell1";
            XMN_ReadTypeWithoutImageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[XMN_ReadTypeWithoutImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.typeWrite = typeWrite;
            cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
            [UIView animateWithDuration:0.5 animations:^{
                cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
            }];
            return cell;
        }
        static NSString *identifier = @"hotCell1";
        XMN_ReadTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[XMN_ReadTypeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.typeWrite = typeWrite;
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    
    XMN_TypeList *typeList = [_dataSourceArray objectAtIndex:indexPath.row];
    if ([typeList.coverimg isEqualToString:@""]) {
        static NSString *identifier = @"cell2";
        XMN_ReadTypeWithoutImageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[XMN_ReadTypeWithoutImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.typeList = typeList;
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    static NSString *identifier = @"hotCell2";
    XMN_ReadTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[XMN_ReadTypeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.typeList = typeList;
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120 * FitHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XMN_ReadDetailViewController *readDetailVC = [[XMN_ReadDetailViewController alloc]init];
    [self.navigationController pushViewController:readDetailVC animated:YES];
    if (_whichOne == 1) {
        XMN_TypeWrite *typeWrite = [_dataSourceArray objectAtIndex:indexPath.row];
        readDetailVC.idString = typeWrite.contentid;
        readDetailVC.titleString = typeWrite.title;
        readDetailVC.imageString = typeWrite.firstimage;
        readDetailVC.contentString = typeWrite.shortcontent;
    }else{
        XMN_TypeList *typeList = [_dataSourceArray objectAtIndex:indexPath.row];
        readDetailVC.idString = typeList.Id;
        readDetailVC.titleString = typeList.title;
        readDetailVC.imageString = typeList.coverimg;
        readDetailVC.contentString = typeList.content;
    }
}

#pragma mark - 解析数据
-(void)getDataByURLString{
    
    if ([_tableView.header isRefreshing]) {
        _start = 0;
    }
    else
    {
        _start++;
    }
    [HTTPMethod getDataByString:@"http://api2.pianke.me/read/columns_detail" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"sort=%@&start=%ld&typeid=%ld&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg&limit=10", _str, _start * 10, _list.type]] WithDataBlock:^(id data) {
        if (data != nil && _start == 0) {
            [_dataSourceArray removeAllObjects];
        }
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            XMN_TypeList *typeList = [[XMN_TypeList alloc]init];
            [typeList setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:typeList];
        }
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_tableView reloadData];
        [_HUD removeFromSuperview];
    }];
}

-(void)getWritingDataByURLString{
    if ([_tableView.header isRefreshing]) {
        _start = 0;
    }
    else
    {
        _start++;
    }

    [HTTPMethod getDataByString:@"http://api2.pianke.me/read/latest" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"sort=%@&start=%ld&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg&limit=10", _str, _start * 10]] WithDataBlock:^(id data) {
        //数据保护
        if (data != nil && _start == 0) {
            [_dataSourceArray removeAllObjects];
        }
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            XMN_TypeWrite *typeWrite = [[XMN_TypeWrite alloc]init];
            [typeWrite setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:typeWrite];
        }
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_tableView reloadData];
        [_HUD removeFromSuperview];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
